import json
from WebEngine.core.runner import Runner
import pika
from tools import settings
class MQConsumer:
    def __init__(self):
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=settings.MQ_CONFIG.get("host"),
                port=settings.MQ_CONFIG.get("port"))
        )
        self.channel = self.connection.channel()
        self.channel.basic_consume(
            queue=settings.MQ_CONFIG.get("queue"),
            on_message_callback=self.run_test,
            auto_ack=True)



    # 获取消息队列中的消息并处理（消费）
    def run_test(self, channel,method, properties, body):
        print("处理消息", body.decode())
        datas = json.loads(body.decode())
        env_config = datas.get("env_config")
        run_suite = datas.get("suite")
        runner = Runner(env_config, run_suite)
        result = runner.run()
        # 保存测试结果
        # 判断是否测试任务中的套件
        if run_suite.get("task_record_id"):

            self.save_task_result(run_suite.get("task_record_id"), result)
        elif run_suite.get("suite_record_id"):
            self.save_suite_result(run_suite.get("suite_record_id"), result)
        else:
            if len(result['run_cases']):
                self.save_case_result(result.get("run_cases"))
            elif len(result['run_suites']):
                self.save_suite_result(result.get("no_run_cases"))
            else:
                self.save_case_result(result)


    def save_task_result(self,task_record_id, result):
        """保存任务执行结果"""
        print(result)

    def save_suite_result(self, suite_record_id, result):
        """保存套件执行结果"""
        print(result)

    def save_case_result(self, result):
        print(result)



    def main(self):
        self.channel.start_consuming()

